package jbl.service.impl;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jbl.dao.ThjDaoI;
import jbl.dao.TkfDaoI;
import jbl.io.excel.ExcelTool;
import jbl.io.excel.HjExcel;
import jbl.model.Thj;
import jbl.model.Tkf;
import jbl.pageModel.DataGrid;
import jbl.pageModel.Hj;
import jbl.service.HjServiceI;
import jbl.util.Encrypt;
import jbl.util.JblTool;
import jbl.util.Json;
import jbl.util.Message;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("hjService")
public class HjServiceImpl implements HjServiceI {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(HjServiceImpl.class);
	
	private ThjDaoI hjDao;
	
	private TkfDaoI kfDao;
	
	@Autowired
	public void setKfDao(TkfDaoI kfDao) {
		this.kfDao = kfDao;
	}
	
	@Autowired
	public void setHjDao(ThjDaoI hjDao) {
		this.hjDao = hjDao;
	}

	@Override
	public DataGrid dataGrid(Hj hj) {
		// TODO Auto-generated method stub
		DataGrid dg = new DataGrid();
		try {
			List<Hj> hjList = new ArrayList<Hj>();
			Map<String, Object> params = new HashMap<String, Object>();
			String hql = " from Thj t where 1=1 ";
			hql = addWhere(hql , hj, params);
			String totalHql = "select count(*) " + hql;
			hql = addOrder(hql , hj);
			List<Thj> list = hjDao.find(hql, params, hj.getPage(), hj.getRows());
			if(null != list && list.size() > 0){
				for(Thj t : list){
					Hj hj1 = new Hj();
					BeanUtils.copyProperties(t, hj1);
					processFK(t, hj1);
					hjList.add(hj1);
				}
			}
			
			dg.setRows(hjList);
			dg.setTotal(hjDao.count(totalHql,params));
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error("查询货架信息error:"+e.getMessage());
		}
		return dg;
	}
	
	private String addOrder(String hql , Hj hj){
		if(null != hj.getSort()){
			hql += " order by t."+hj.getSort() +" " + hj.getOrder();
		}
		return hql;
	}
	
	private String addWhere(String hql , Hj hj , Map<String, Object> params){
		if(null != hj.getKfID()&&!"".equals(hj.getKfID())){
			hql += " and t.tkf.id=:kfID ";
			params.put("kfID", hj.getKfID());
		}
		return hql;
	}
	
	private void processFK(Thj t , Hj hj){
		Tkf kf = t.getTkf();
		if(null != kf){
			List<Object> list = new ArrayList<Object>();
			list.add(kf.getName());
			list.add(kf.getId());
			list.add(kf.getFlag());
			hj.setKfName(kf.getName());
			hj.setKfList(list);
		}
	}

	@Override
	public Json delete(Hj hj) {
		Json j = new Json();
		
		try{
			String ids = hj.getIds();
			System.out.println(ids+"--");
			if(null != ids){
				for(String id : ids.split(",")){
					if(!"".equals(id.trim())){
						Thj thj = hjDao.get(Thj.class, id);
						hjDao.delete(thj);
					}
				}
			}
			j.setMsg("删除成功");
			j.setSuccess(true);
		}catch(Exception e){
			e.printStackTrace();
			j.setMsg("删除失败");
		}
		return j;
	}

	@Override
	public Json update(Hj hj) {
		// TODO Auto-generated method stub
		Json j = new Json();
		try {
			Thj thj = new Thj();
			BeanUtils.copyProperties(hj, thj);
			List<Object> list = hj.getKfList();
			if(null != list){
				Tkf tkf = new Tkf();
				tkf.setId(list.get(0).toString());
				thj.setTkf(tkf);
			}
			hjDao.update(thj);
			j.setMsg("更新成功");
			j.setSuccess(true);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error("更新失败:"+e.getMessage());
			j.setMsg("更新失败");
		}
		return j;
	}

	@Override
	public Json add(Hj hj) {
		Json j = new Json();
		try {
			Thj thj = new Thj();
			BeanUtils.copyProperties(hj, thj);
			List<Object> list = hj.getKfList();
			if(null != list){
				Tkf tkf = new Tkf();
				tkf.setId(list.get(0).toString());
				thj.setTkf(tkf);
			}
			thj.setId(Encrypt.createUUID());
			hjDao.save(thj);
			j.setMsg("添加成功");
			j.setSuccess(true);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error("添加失败:"+e.getMessage());
			j.setMsg("添加失败");
		}
		return j;
	}

	@Override
	public List<HjExcel> findAll(Hj hj) {
		List<HjExcel> hjList = new ArrayList<HjExcel>();
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			String hql = " from Thj t where 1=1 ";
			hql = addWhere(hql , hj, params);
			int xh = 1;

			List<Thj> list = hjDao.find(hql, params);
			if(null != list && list.size() > 0){
				for(Thj t : list){
					HjExcel hj1 = new HjExcel();
					BeanUtils.copyProperties(t, hj1);
					if(null != t.getTkf()){
						hj1.setKfName(t.getTkf().getName());
					}
					hj1.setFlag(JblTool.toFlag(t.getFlag()));
					hj1.setId(xh+"");
					xh++;
					hjList.add(hj1);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error("查询货架信息error:"+e.getMessage());
		}
		return hjList;
	}

	@Override
	public Json upHjFile(Hj hj) {
		Json j = new Json();
		String kfHql = " from Tkf t ";
		List<Tkf> kfList = kfDao.find(kfHql);
		
		Workbook book = null; 
		try {
			List<FileItem> list = ExcelTool.getItemFile();
			for(FileItem item:list){
				if("hj_upload_excel".equals(item.getFieldName().trim())){
					hj.setFilename(item.getName());
					try {
						book = ExcelTool.createWorkBook(item.getInputStream(), hj.getFilename());//解析上传文件Excel
						 Sheet sheet =  book.getSheetAt(0);	
						 List<Thj> hjList = new ArrayList<Thj>();
				         for (int i = 1; i <= sheet.getLastRowNum(); i++) { //解析成功  输出
				             Row ros = sheet.getRow(i); 
				             String ros1 = String.valueOf(ros.getCell(1)).trim();	
				             String ros2 = String.valueOf(ros.getCell(2)).trim();
				             String ros3 = String.valueOf(ros.getCell(3)).trim();
				             String ros4 = String.valueOf(ros.getCell(4)).trim();
				             String ros5 = String.valueOf(ros.getCell(5)).trim();
				             String ros6 = String.valueOf(ros.getCell(6)).trim();

				             
				             Thj hj1 = new Thj();
				             if(!"null".equals(ros1) && !"".equals(ros1)){
				            	 hj1.setNumberID(ros1);
				             }else{
				            	 j.setMsg("货架编号不能为空：第2列,第"+i+"行!");
				            	 return j; 
				             }
				             
				             Tkf kf = null;
				             for(Tkf t : kfList){
				            	 if(t.getName().equals(ros2.trim())){
				            		 kf = t;
				            	 }
				             }
				             if(null == kf){
				            	 j.setMsg("库房信息数据库未记录：第3列,第"+i+"行!");
				            	 return j;
				             }else{
				            	 hj1.setTkf(kf);
				             }
				             if(!"null".equals(ros3) && !"".equals(ros3)){
				            	 hj1.setName(ros3);
				             }else{
				            	 j.setMsg("货架名称不能为空：第4列,第"+i+"行!");
				            	 return j; 
				             }
				             hj1.setBz(ExcelTool.toNyStr(ros4));
				             if(!"null".equals(ros5) && !"".equals(ros5)){
				            	 if(ros5.equals(Message.KQ_ZT)){
				            		 hj1.setFlag("T");
				            	 }else if(ros5.equals(Message.GB_ZT)){
				            		 hj1.setFlag("F");
				            	 }else{
				            		 j.setMsg("状态信息不正确：第6列,第"+i+"行!");
					            	 return j; 
				            	 }
				             }else{
				            	 hj1.setFlag("T");
				             }
				             if(!"null".equals(ros6) && !"".equals(ros6)){
				            	 hj1.setCjsj(Timestamp.valueOf(ros6));
				             }else{
				            	 hj1.setCjsj(Timestamp.valueOf(Message.timeFormat.format(new Date())));
				             }
				             hj1.setId(Encrypt.createUUID());
				             hjList.add(hj1);
				         } 
				         for(Thj t : hjList){
				        	 hjDao.save(t);
				         }
				         j.setMsg("导入成功");
				         j.setSuccess(true);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
						j.setMsg("文件未找到!");
						return j;
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						j.setMsg("IO中断!");
						return j;
					}
				}
			}
			
		} catch (FileUploadException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			j.setMsg("导入失败");
		}
		
		return j;
	}

	@Override
	public List<Hj> comboboxInfo() {
		List<Hj> hjList = new ArrayList<Hj>();
		try {
			
			String hql = " from Thj t ";
			List<Thj> list = hjDao.find(hql);
			if(null != list && list.size() > 0){
				for(Thj t : list){
					Hj hj1 = new Hj();
					BeanUtils.copyProperties(t, hj1);
					processFK(t, hj1);
					hjList.add(hj1);
				}
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			logger.error("查询货架信息error:"+e.getMessage());
		}
		return hjList;
	}
}
